﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ProjectJourney
{
    public class Landscape : MonoBehaviour
    {
        [SerializeField] Vector2 _rangeX;
        [SerializeField] Vector2 _rangeY;
        [SerializeField] bool _opposite;
        float _lengthX;
        float _lengthY;
        Vector3 _origin;

        private void Awake()
        {
            var extents = GetComponent<SpriteRenderer>().sprite.bounds.extents;
            _lengthX = extents.x * 2f;
            _lengthY = extents.y * 2f;
            _origin = transform.position;
        }

        private void FixedUpdate()
        {
            float distanceX = Camera.main.transform.position.x - _rangeX.x;
            float distanceY = Camera.main.transform.position.y - _rangeY.x;
            float maxDistanceX = _rangeX.y - _rangeX.x;
            float maxDistanceY = _rangeY.y - _rangeY.x;
            float viewportX = Camera.main.orthographicSize * 4f;
            float viewportY = Camera.main.orthographicSize * 2f;
            Vector3 offset = Vector3.zero;
            if (_opposite)
            {
                if (maxDistanceX != 0)
                {
                    offset.x = distanceX / maxDistanceX * (maxDistanceX + viewportX + (_lengthX - viewportX) * 2f - _lengthX);
                }
                if (maxDistanceY != 0)
                {
                    offset.y = distanceY / maxDistanceY * (maxDistanceY + viewportY + (_lengthY - viewportY) * 2f - _lengthY);
                }
            }
            else
            {
                if (maxDistanceX != 0)
                {
                    offset.x = distanceX / maxDistanceX * (maxDistanceX + viewportX - _lengthX);
                }
                if (maxDistanceY != 0)
                {
                    offset.y = distanceY / maxDistanceY * (maxDistanceY + viewportY - _lengthY);
                }
            }
            transform.position = _origin + offset;
        }
    }
}
